package shape;

import java.util.Stack;

import javax.media.opengl.GL2;
import javax.swing.text.html.ListView;

import util.Util;
import window.Axis;
import window.Hue;

import com.jogamp.opengl.util.gl2.GLUT;


public class Light extends Shape {
	private int index;
	
	private static final int LIGHTS[] = { GL2.GL_LIGHT0, GL2.GL_LIGHT1, GL2.GL_LIGHT2,
										  GL2.GL_LIGHT3, GL2.GL_LIGHT4, GL2.GL_LIGHT5 };
	
	public static final int MAX_LIGHTS = LIGHTS.length;
	
	private static boolean indexUsed[] = new boolean[LIGHTS.length];
	
	private static final float[] BLACK = {0.0f, 0.0f, 0.0f, 1.0f};
	private static final float[] WHITE = {1.0f, 1.0f, 1.0f, 1.0f};
	
	public Light( double x, double y, double z ) throws Exception {
		super(x, y, z);
		this.index = getFreeIndex();
	}
	
	public Light() throws Exception {
		this(0,0,0);
	}
	
	public void release() {
		indexUsed[index] = false;
	}
	
	public void apply( GL2 gl ) {
		float[] vambient 	= { (float) color[Hue.R]/10, (float) color[Hue.G]/10, (float) color[Hue.B]/10, 1.0f };
		float[] vdiffuse 	= { (float) color[Hue.R]/1, (float) color[Hue.G]/1, (float) color[Hue.B]/1, 1.0f };
		float[] vpos 		= { (float) position[Axis.X], (float) position[Axis.Y], (float) position[Axis.Z], 1.0f };

		gl.glLightfv(LIGHTS[index], GL2.GL_AMBIENT, vambient, 0);
		gl.glLightfv(LIGHTS[index], GL2.GL_DIFFUSE, vdiffuse, 0);
		gl.glLightfv(LIGHTS[index], GL2.GL_POSITION, vpos, 0);
		
		//gl.glEnable(LIGHTS[index]);
	}
	
	@Override
	protected void draw( GL2 gl ) {
		Util.glut.glutSolidSphere(0.05, 4, 2);
	}
	
	@Override
	protected void drawSelected( GL2 gl ) {
		Util.glut.glutWireSphere(0.05, 4, 2);
	}
	
	private static int getFreeIndex() throws Exception {
		for (int i = 0; i < indexUsed.length; i++)
			if (!indexUsed[i]) {
				indexUsed[i] = true;
				return i;
			}
		
		throw new Exception("No available light index");
	}
	
	public static void enableLights(GL2 gl) {
		for (int i = 0; i < LIGHTS.length; i++) {
			if (indexUsed[i])
				gl.glEnable(LIGHTS[i]);
			else
				gl.glDisable(LIGHTS[i]);
		}
	}
	
	public int getIndex() {
		return index;
	}

}
